package com.example.util.common;

import com.example.config.common.TraceFilter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/7/2 16:42
 */
public class ThreadMdcUtil {

    /**
     * 日志跟踪id名。
     */
    public static final String LOG_TRACE_ID = "traceId";


    public static String generatorUuid() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-","");
        String id = uuid + "-" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        return id.toUpperCase();
    }

    public static void setTraceIdIfAbsent() {
        if (StringUtils.isBlank(getTranceId())) {
            String uuid = generatorUuid();
            MDC.put(LOG_TRACE_ID,uuid);
        }
    }

    public static void setTraceId() {
        String uuid = generatorUuid();
        MDC.put(LOG_TRACE_ID,uuid);
    }

    public static void removeTranceId() {
        MDC.remove(LOG_TRACE_ID);
    }


    public static String getTranceId() {
        return MDC.get(LOG_TRACE_ID);
    }


    public static <T> Callable<T> wrap(final Callable<T> callable,final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    public static Runnable wrap(final Runnable runnable,final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }

}
